﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Utility.NodeGraphs;
using Utility.Math;
using Utility.Inspector;
using System.Reflection;
using System;
using System.Linq;

namespace Utility.BehaviourTree
{
	[NodeEditor (typeof (BTSetting_Node))]
	public class BTSetting_NodeEditor : TreeNodeEditor
	{
		public override Vector2 GetContentSize (Node node)
		{
			BTSetting_Node btNode = (BTSetting_Node)node;

			float w = 200;
			float h_line = EditorGUIUtility.singleLineHeight;
			ParameterInfo[] parameters;
			if (BTSetting_NodeGraph.TryGetTypeParams (btNode.typeName, out parameters))
			{
				int lines = 1 + parameters.Length;
				float h = (h_line + LinePadding) * lines - LinePadding;


				return new Vector2 (w, h);
			}
			else
			{
				return new Vector2 (w, h_line * 3);
			}
		}

		protected override void DrawContents (Rect contentRect, Node node)
		{
			BTSetting_Node btNode = (BTSetting_Node)node;
			Rect rect = contentRect.ResizeHeight (EditorGUIUtility.singleLineHeight);

			using (EditorGUIWidthScope.NewLabelWidth (80))
			{
				//constructor parameters
				ParameterInfo[] parameters;
				if (BTSetting_NodeGraph.TryGetTypeParams (btNode.typeName, out parameters))
				{
					//node name
					btNode.nodeName = EditorGUI.TextField (rect, "Name", btNode.nodeName);

					//init param list
					if (btNode.parameters.Length != parameters.Length)
					{
						btNode.parameters = new string[parameters.Length];
						for (int i = 0; i < parameters.Length; i++)
						{
							btNode.parameters[i] = parameters[i].DefaultValue.ToString ();
						}
					}
					foreach (var param in parameters)
					{
						rect = rect.ShiftUp ().ShiftUp (LinePadding);

						int i = param.Position;
						if (param.ParameterType == typeof (int))
						{
							int oldVal = int.TryParse (btNode.parameters[i], out oldVal) ? oldVal : default;
							btNode.parameters[i] = EditorGUI.IntField (rect, param.Name, oldVal).ToString ();
						}
						if (param.ParameterType == typeof (float))
						{
							float oldVal = float.TryParse (btNode.parameters[i], out oldVal) ? oldVal : default;
							btNode.parameters[i] = EditorGUI.FloatField (rect, param.Name, oldVal).ToString ();
						}
						if (param.ParameterType == typeof (bool))
						{
							bool oldVal = bool.TryParse (btNode.parameters[i], out oldVal) ? oldVal : default;
							btNode.parameters[i] = EditorGUI.Toggle (rect, param.Name, oldVal).ToString ();
						}
						if (param.ParameterType == typeof (string))
						{
							btNode.parameters[i] = EditorGUI.TextField (rect, param.Name, btNode.parameters[i]);
						}
					}
				}
				else
				{
					EditorGUI.HelpBox (contentRect, "Invalid node type:\n" + btNode.typeName, MessageType.Error);
				}
			}
		}

		#region menu
		protected override GenericMenu BuildPortContextMenu (NodePort port)
		{
			return base.BuildPortContextMenu (port);
		}

		#endregion
	}
}